package org.example.algorithm.array;

public class MaxSubArraySolution {

    public int maxSubArray(int[] nums) {
        int prefixSum = 0;
        int minPrefixSum = 0;
        int ans = Integer.MIN_VALUE;
        for (int i=0;i<nums.length;i++) {
            prefixSum += nums[i];
            ans = Math.max(ans, prefixSum-minPrefixSum);
            minPrefixSum = Math.min(minPrefixSum, prefixSum);
        }
        return ans;
    }

    public int maxSubArray2(int[] nums) {
        int preSum = 0;
        int ans = Integer.MIN_VALUE;
        for (int i=0;i<nums.length;i++) {
            if (preSum > 0) {
                preSum = preSum + nums[i];
            } else {
                preSum = nums[i];
            }
            ans = Math.max(ans, preSum);
        }
        return ans;
    }

    public int maxSubArray3(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i=1;i<nums.length;i++) {
            if (dp[i-1] < 0) {
                dp[i] = nums[i];
            } else {
                dp[i] = nums[i] + dp[i-1];
            }
        }
        int ans = Integer.MIN_VALUE;
        for (int num: dp) {
            ans = Math.max(ans, num);
        }
        return ans;
    }
}
